package com.lz.sports.ui

import android.os.Bundle
import android.widget.Toast
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lz.comm.BR
import com.lz.helper.idcard.IDCardInfo
import com.lz.library.base.BaseActivity
import com.lz.sports.LogUtils
import com.lz.sports.R
import com.lz.sports.bean.CommonModel
import com.lz.sports.bean.Examinee
import com.lz.sports.core.ProjectManager
import com.lz.sports.core.VerifyManager
import com.lz.sports.databinding.ActSignInBinding
import com.lz.sports.dialog.SignSuccessDialog
import com.lz.sports.ui.checkmodel.ExamineeFinder
import com.lz.sports.ui.checkmodel.FaceIdentifyFragment
import com.lz.sports.ui.checkmodel.FeatureResult
import com.lz.sports.ui.checkmodel.IdCardFragment
import com.lz.sports.utils.ToastUtils
import com.lz.sports.vm.SignInViewModel

//签到
class SignInActivity : BaseActivity<SignInViewModel, ActSignInBinding>(), ExamineeFinder {

    override fun getLayoutRes(): Int = R.layout.act_sign_in

    override fun getVMVariableId(): Int = BR.vm

    private var signInDialog: SignSuccessDialog? = null

    override fun initObserve() {
        viewModel.examinee.observe(this) {
            if (it == null) {
                ToastUtils.showMyToast(R.string.inspect_in_none, Toast.LENGTH_SHORT)
            } else {
                ToastUtils.showMyToast(R.string.inspect_sign, Toast.LENGTH_SHORT)
                signInDialog = SignSuccessDialog.show(this@SignInActivity, it)
            }
        }

        LiveEventBus.get("idCardInfo", IDCardInfo::class.java).observe(this) {
//            LogUtils.i("name = ${it.name}")
            if (signInDialog?.dialog?.isShowing == true || viewModel.isFinding) {
                LogUtils.i("pre examinee is show")
            } else {
                viewModel.findExaminee(it)
            }
        }

        LiveEventBus.get("FaceIdentify", FeatureResult::class.java).observe(this) {
            if (signInDialog?.dialog?.isShowing == true) {
                signInDialog?.dismiss()
            }
            signInDialog = SignSuccessDialog.show(this@SignInActivity, it.examinee)
            viewModel.saveExaminee(it)
        }
    }

    override fun initData(savedState: Bundle?) {
        when (val type = VerifyManager.signInModel().type) {
            CommonModel.ID_CARD_EXAM, CommonModel.ID_CARD_ID, CommonModel.ID_CARD_FACE_EXAM, CommonModel.ID_CARD_AND -> {
                val fragment = FaceIdentifyFragment.newInstance(type, ProjectManager.personThreshold(), ProjectManager.faceThreshold())
                supportFragmentManager.beginTransaction().add(R.id.fl, fragment).commitNow()
            }
            CommonModel.ID_CARD -> {
                supportFragmentManager.beginTransaction().add(R.id.fl, IdCardFragment()).commitNow()
            }
        }
    }

    override fun findExamineeByIDCardInfo(idCardInfo: IDCardInfo): Examinee? =
        viewModel.findIdentifyExaminee(idCardInfo)
}